import { z } from 'zod';
import { router, publicProcedure } from '../trpc';
import { protectedProcedure, adminProcedure } from '../middleware';
import { rechargeService } from '../../services/rechargeService';
import { createSuccessResponse, createErrorResponse } from '../../utils/response';
import { telegramService, TelegramNotificationData } from '../../services/telegramService';
import { RechargeStatus, PaymentChannel } from '@prisma/client';
import { paymentService } from '../../services/paymentService';
import { prisma } from '../../db';
import { Logger } from '../../utils/logger';

// Input validation schemas
const createRechargeOrderSchema = z.object({
  userId: z.number().int().positive('User ID must be a positive integer'),
  amount: z.number().positive('Recharge amount must be greater than 0').max(100000, 'Recharge amount cannot exceed 100000'),
  paymentChannel: z.nativeEnum(PaymentChannel, {
    errorMap: () => ({ message: 'Payment channel must be TOPPAY, PAY668, LSPPAY, or HUIFENG' })
  }),
  paymentMethod: z.enum(['BankTransfer', 'qrPay'], {
    errorMap: () => ({ message: 'Payment method must be BankTransfer or qrPay' })
  }),
  transAccNo: z.string().min(1, 'Bank card number cannot be empty').regex(/^\d{10,20}$/, 'Bank card number must be 10-20 digits'), // Required for all payment methods
  paymentName: z.string().min(1, 'Payer real name cannot be empty'), // Required
  bankCode: z.string().optional(), // Optional for LSPPAY, required for others (validation will be done in mutation)
  customerEmail: z.string().email('Email format is incorrect').optional(), // Customer email (optional)
  customerPhone: z.string().min(1, 'Phone number cannot be empty').optional(), // Customer phone (optional)
  extendParam: z.string().optional(), // Pass-through parameter (uploaded content will be returned as is)
  createdByName: z.string().min(2, 'Creator name must be at least 2 characters').max(50, 'Creator name cannot exceed 50 characters'), // Order creator name (required)
});

const queryRechargeOrdersSchema = z.object({
  orderId: z.string().optional(),
  userId: z.number().int().positive().optional(),
  status: z.nativeEnum(RechargeStatus).optional(),
  createdByUserId: z.number().int().positive().optional(),
  createdByName: z.string().optional(), // 开单客服名称搜索
  page: z.number().int().positive().default(1),
  limit: z.number().int().positive().max(100).default(20),
});

const topPayNotificationSchema = z.object({
  code: z.string(),
  msg: z.string(),
  status: z.string(),
  method: z.string(),
  platOrderNum: z.string(),
  orderNum: z.string(),
  payMoney: z.string(),
  payFee: z.string(),
  transAccNo: z.string().optional(),
  platSign: z.string(),
});

const pay668NotificationSchema = z.object({
  payOrderId: z.string(),
  mchOrderNo: z.string(),
  orderState: z.number(),
  amount: z.string(),
  customerName: z.string(),
  customerEmail: z.string(),
  customerPhone: z.string(),
  wayCode: z.string().optional(),
  extParam: z.string().optional(),
  sign: z.string(),
});

export const rechargeRouter = router({
  /**
   * 创建充值订单
   */
  create: protectedProcedure
    .input(createRechargeOrderSchema)
    .mutation(async ({ input, ctx }) => {
      try {
        // Validate bankCode based on payment channel
        if (input.paymentChannel !== 'LSPPAY' && !input.bankCode) {
          return createErrorResponse(
            `Bank code is required for ${input.paymentChannel}`,
            'VALIDATION_ERROR'
          );
        }

        const result = await rechargeService.createRechargeOrder({
          userId: input.userId,
          amount: input.amount,
          paymentChannel: input.paymentChannel,
          paymentMethod: input.paymentMethod,
          createdByUserId: ctx.user.userId,
          createdByName: input.createdByName,
          transAccNo: input.transAccNo,
          paymentName: input.paymentName,
          bankCode: input.bankCode || '', // Provide empty string if not provided (for LSPPAY)
          customerEmail: input.customerEmail,
          customerPhone: input.customerPhone,
          extendParam: input.extendParam,
        });

        return createSuccessResponse(result, 'Recharge order created successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to create recharge order',
          'RECHARGE_CREATE_ERROR'
        );
      }
    }),

  /**
   * Query recharge orders
   */
  query: protectedProcedure
    .input(queryRechargeOrdersSchema)
    .query(async ({ input, ctx }) => {
      try {
        // Non-admin users can only view orders they created
        const queryInput = {
          ...input,
          createdByUserId: ctx.user.role === 'ADMIN' || ctx.user.role === 'SUB_ADMIN'
            ? input.createdByUserId
            : ctx.user.userId,
        };

        const result = await rechargeService.queryRechargeOrders(queryInput);
        return createSuccessResponse(result, 'Recharge orders queried successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to query recharge orders',
          'RECHARGE_QUERY_ERROR'
        );
      }
    }),

  /**
   * Get recharge record by order ID
   */
  getByOrderId: protectedProcedure
    .input(z.object({
      orderId: z.string().min(1, 'Order ID cannot be empty'),
    }))
    .query(async ({ input, ctx }) => {
      try {
        const record = await rechargeService.getRechargeRecordByOrderId(input.orderId);

        if (!record) {
          return createErrorResponse('Order does not exist', 'ORDER_NOT_FOUND');
        }

        // Check permissions: only admin or order creator can view
        if (ctx.user.role !== 'ADMIN' && ctx.user.role !== 'SUB_ADMIN' &&
            record.createdByUserId !== ctx.user.userId) {
          return createErrorResponse('No permission to view this order', 'PERMISSION_DENIED');
        }

        return createSuccessResponse(record, 'Order details retrieved successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to get order details',
          'RECHARGE_GET_ERROR'
        );
      }
    }),

  /**
   * 获取用户充值统计
   */
  getUserStats: protectedProcedure
    .input(z.object({
      userId: z.number().int().positive(),
    }))
    .query(async ({ input, ctx }) => {
      try {
        // 检查权限：只有管理员或用户本人可以查看统计
        if (ctx.user.role !== 'ADMIN' && ctx.user.role !== 'SUB_ADMIN' && 
            input.userId !== ctx.user.userId) {
          return createErrorResponse('无权限查看此用户统计', 'PERMISSION_DENIED');
        }

        const stats = await rechargeService.getUserRechargeStats(input.userId);
        return createSuccessResponse(stats, '获取用户充值统计成功');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : '获取用户充值统计失败',
          'RECHARGE_STATS_ERROR'
        );
      }
    }),

  /**
   * Admin query all orders
   */
  adminQuery: adminProcedure
    .input(queryRechargeOrdersSchema)
    .query(async ({ input }) => {
      try {
        const result = await rechargeService.queryRechargeOrders(input);
        return createSuccessResponse(result, 'Admin recharge orders queried successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Admin recharge orders query failed',
          'ADMIN_RECHARGE_QUERY_ERROR'
        );
      }
    }),

  /**
   * TopPay async notification handling (public interface)
   */
  topPayNotify: publicProcedure
    .input(topPayNotificationSchema)
    .mutation(async ({ input }) => {
      try {
        await rechargeService.handleTopPayNotification(input);

        // TopPay requires returning SUCCESS string
        return 'SUCCESS';
      } catch (error) {
        console.error('TopPay notification processing failed:', error);
        // Return failure, TopPay will retry
        throw new Error('FAILED');
      }
    }),

  /**
   * 668Pay async notification handling (public interface)
   */
  pay668Notify: publicProcedure
    .input(pay668NotificationSchema)
    .mutation(async ({ input }) => {
      try {
        await rechargeService.handlePay668Notification(input);

        // 668Pay requires returning SUCCESS string
        return 'SUCCESS';
      } catch (error) {
        console.error('668Pay notification processing failed:', error);
        // Return failure, 668Pay will retry
        throw new Error('FAILED');
      }
    }),

  /**
   * Huifeng async notification handling (public interface)
   */
  huifengNotify: publicProcedure
    .input(z.record(z.any())) // 汇沣支付回调数据结构
    .mutation(async ({ input }) => {
      try {
        await rechargeService.handlePaymentNotification(PaymentChannel.HUIFENG, input);

        // 汇沣支付要求返回lowercase "success"
        return 'success';
      } catch (error) {
        console.error('Huifeng notification processing failed:', error);
        // Return failure, Huifeng will retry
        throw new Error('FAILED');
      }
    }),

  /**
   * Manually query TopPay order status
   */
  queryTopPayStatus: protectedProcedure
    .input(z.object({
      orderId: z.string().min(1, 'Order ID cannot be empty'),
    }))
    .mutation(async ({ input, ctx }) => {
      try {
        const record = await rechargeService.getRechargeRecordByOrderId(input.orderId);

        if (!record) {
          return createErrorResponse('Order does not exist', 'ORDER_NOT_FOUND');
        }

        // Check permissions
        if (ctx.user.role !== 'ADMIN' && ctx.user.role !== 'SUB_ADMIN' &&
            record.createdByUserId !== ctx.user.userId) {
          return createErrorResponse('No permission to query this order', 'PERMISSION_DENIED');
        }

        // Call TopPay query API
        const topPayResult = await rechargeService.queryTopPayOrderStatus(
          input.orderId,
          record.platOrderNum || undefined
        );

        let cardSellResult = null;

        // 检查是否需要自动发金币
        if (topPayResult.success) {
          // 重新获取最新的订单记录（可能在查询过程中状态已更新）
          const updatedRecord = await rechargeService.getRechargeRecordByOrderId(input.orderId);

          if (updatedRecord &&
              updatedRecord.status === 'COMPLETED' &&
              !updatedRecord.sellCardStatus) {

            Logger.info(`🎯 管理端查询发现订单 ${input.orderId} 支付成功但未发金币，开始自动发金币流程`, {
              orderId: input.orderId,
              trigger: 'admin_query'
            });

            try {
              cardSellResult = await rechargeService.executeCardSellAndNotify(input.orderId);
              Logger.info(`✅ 管理端查询触发的自动发金币完成`, {
                orderId: input.orderId,
                sellCardSuccess: cardSellResult.sellCardSuccess,
                telegramSent: cardSellResult.telegramSent,
                message: cardSellResult.message,
                trigger: 'admin_query'
              });
            } catch (error) {
              Logger.error(`❌ 管理端查询触发的自动发金币失败`, error, {
                orderId: input.orderId,
                trigger: 'admin_query'
              });
              cardSellResult = {
                success: false,
                message: `自动发金币失败: ${error instanceof Error ? error.message : '未知错误'}`
              };
            }
          }
        }

        return createSuccessResponse({
          localRecord: record,
          topPayResult,
          cardSellResult, // 包含发金币结果
        }, 'TopPay order status queried successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'TopPay order status query failed',
          'TOPPAY_QUERY_ERROR'
        );
      }
    }),

  /**
   * Manually query 668Pay order status
   */
  queryPay668Status: protectedProcedure
    .input(z.object({
      orderId: z.string().min(1, 'Order ID cannot be empty'),
    }))
    .mutation(async ({ input, ctx }) => {
      try {
        const record = await rechargeService.getRechargeRecordByOrderId(input.orderId);

        if (!record) {
          return createErrorResponse('Order does not exist', 'ORDER_NOT_FOUND');
        }

        // Check permissions
        if (ctx.user.role !== 'ADMIN' && ctx.user.role !== 'SUB_ADMIN' &&
            record.createdByUserId !== ctx.user.userId) {
          return createErrorResponse('No permission to query this order', 'PERMISSION_DENIED');
        }

        // Call 668Pay query API
        const pay668Result = await rechargeService.queryPay668OrderStatus(
          input.orderId,
          record.platOrderNum || undefined
        );

        let cardSellResult = null;

        // 检查是否需要自动发金币 - Pay668查询成功的条件是code为0
        if (pay668Result.code === 0) {
          // 重新获取最新的订单记录（可能在查询过程中状态已更新）
          const updatedRecord = await rechargeService.getRechargeRecordByOrderId(input.orderId);

          if (updatedRecord &&
              updatedRecord.status === 'COMPLETED' &&
              !updatedRecord.sellCardStatus) {

            Logger.info(`🎯 管理端查询发现订单 ${input.orderId} 支付成功但未发金币，开始自动发金币流程`, {
              orderId: input.orderId,
              trigger: 'admin_query'
            });

            try {
              cardSellResult = await rechargeService.executeCardSellAndNotify(input.orderId);
              Logger.info(`✅ 管理端查询触发的自动发金币完成`, {
                orderId: input.orderId,
                sellCardSuccess: cardSellResult.sellCardSuccess,
                telegramSent: cardSellResult.telegramSent,
                message: cardSellResult.message,
                trigger: 'admin_query'
              });
            } catch (error) {
              Logger.error(`❌ 管理端查询触发的自动发金币失败`, error, {
                orderId: input.orderId,
                trigger: 'admin_query'
              });
              cardSellResult = {
                success: false,
                message: `自动发金币失败: ${error instanceof Error ? error.message : '未知错误'}`
              };
            }
          }
        }

        return createSuccessResponse({
          localRecord: record,
          pay668Result,
          cardSellResult, // 包含发金币结果
        }, '668Pay order status queried successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : '668Pay order status query failed',
          'PAY668_QUERY_ERROR'
        );
      }
    }),

  /**
   * Manually query LSPPAY order status
   */
  queryLspPayStatus: protectedProcedure
    .input(z.object({
      orderId: z.string().min(1, 'Order ID cannot be empty'),
    }))
    .mutation(async ({ input, ctx }) => {
      try {
        const record = await rechargeService.getRechargeRecordByOrderId(input.orderId);

        if (!record) {
          return createErrorResponse('Order does not exist', 'ORDER_NOT_FOUND');
        }

        // Check permissions
        if (ctx.user.role !== 'ADMIN' && ctx.user.role !== 'SUB_ADMIN' &&
            record.createdByUserId !== ctx.user.userId) {
          return createErrorResponse('No permission to query this order', 'PERMISSION_DENIED');
        }

        // Call LSPPAY query API
        const lspPayResult = await rechargeService.queryLspPayOrderStatus(
          input.orderId,
          record.platOrderNum || undefined
        );

        let cardSellResult = null;

        console.log(`订单 ${input.orderId} LSPPAY 查询结果:`, lspPayResult);
        // 检查是否需要自动发金币 - LSPPAY查询成功的条件是code为0
        if (lspPayResult.code === 0) {
          // 重新获取最新的订单记录（可能在查询过程中状态已更新）
          const updatedRecord = await rechargeService.getRechargeRecordByOrderId(input.orderId);

          if (updatedRecord &&
              updatedRecord.status === 'COMPLETED' &&
              !updatedRecord.sellCardStatus) {

            Logger.info(`🎯 管理端查询发现订单 ${input.orderId} 支付成功但未发金币，开始自动发金币流程`, {
              orderId: input.orderId,
              trigger: 'admin_query'
            });

            try {
              cardSellResult = await rechargeService.executeCardSellAndNotify(input.orderId);
              Logger.info(`✅ 管理端查询触发的自动发金币完成`, {
                orderId: input.orderId,
                sellCardSuccess: cardSellResult.sellCardSuccess,
                telegramSent: cardSellResult.telegramSent,
                message: cardSellResult.message,
                trigger: 'admin_query'
              });
            } catch (error) {
              Logger.error(`❌ 管理端查询触发的自动发金币失败`, error, {
                orderId: input.orderId,
                trigger: 'admin_query'
              });
              cardSellResult = {
                success: false,
                message: `自动发金币失败: ${error instanceof Error ? error.message : '未知错误'}`
              };
            }
          }
        }

        return createSuccessResponse({
          localRecord: record,
          lspPayResult,
          cardSellResult, // 包含发金币结果
        }, 'LSPPAY order status queried successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'LSPPAY order status query failed',
          'LSPPAY_QUERY_ERROR'
        );
      }
    }),

  /**
   * Manually query Huifeng order status
   */
  queryHuifengStatus: protectedProcedure
    .input(z.object({
      orderId: z.string().min(1, 'Order ID cannot be empty'),
    }))
    .mutation(async ({ input, ctx }) => {
      try {
        const record = await rechargeService.getRechargeRecordByOrderId(input.orderId);

        if (!record) {
          return createErrorResponse('Order does not exist', 'ORDER_NOT_FOUND');
        }

        // Check permissions
        if (ctx.user.role !== 'ADMIN' && ctx.user.role !== 'SUB_ADMIN' &&
            record.createdByUserId !== ctx.user.userId) {
          return createErrorResponse('No permission to query this order', 'PERMISSION_DENIED');
        }

        // Call Huifeng query API
        const huifengResult = await rechargeService.queryHuifengOrderStatus(
          input.orderId,
          record.platOrderNum || undefined
        );

        let cardSellResult = null;

        console.log(`订单 ${input.orderId} 汇沣支付查询结果:`, huifengResult);

        // 检查是否需要自动发金币 - 汇沣支付查询成功的条件是code为0
        if (huifengResult.code === 0) {
          // 重新获取最新的订单记录（可能在查询过程中状态已更新）
          const updatedRecord = await rechargeService.getRechargeRecordByOrderId(input.orderId);

          if (updatedRecord &&
              updatedRecord.status === 'COMPLETED' &&
              !updatedRecord.sellCardStatus) {

            Logger.info(`🎯 管理端查询发现订单 ${input.orderId} 支付成功但未发金币，开始自动发金币流程`, {
              orderId: input.orderId,
              trigger: 'admin_query'
            });

            try {
              cardSellResult = await rechargeService.executeCardSellAndNotify(input.orderId);
              Logger.info(`✅ 管理端查询触发的自动发金币完成`, {
                orderId: input.orderId,
                sellCardSuccess: cardSellResult.sellCardSuccess,
                telegramSent: cardSellResult.telegramSent,
                message: cardSellResult.message,
                trigger: 'admin_query'
              });
            } catch (error) {
              Logger.error(`❌ 管理端查询触发的自动发金币失败`, error, {
                orderId: input.orderId,
                trigger: 'admin_query'
              });
              cardSellResult = {
                success: false,
                message: `自动发金币失败: ${error instanceof Error ? error.message : '未知错误'}`
              };
            }
          }
        }

        return createSuccessResponse({
          localRecord: record,
          huifengResult,
          cardSellResult, // 包含发金币结果
        }, 'Huifeng order status queried successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Huifeng order status query failed',
          'HUIFENG_QUERY_ERROR'
        );
      }
    }),

  /**
   * Manually query NASKI order status
   */
  queryNaskiStatus: protectedProcedure
    .input(z.object({
      orderId: z.string().min(1, 'Order ID cannot be empty'),
    }))
    .mutation(async ({ input, ctx }) => {
      try {
        const record = await rechargeService.getRechargeRecordByOrderId(input.orderId);

        if (!record) {
          return createErrorResponse('Order does not exist', 'ORDER_NOT_FOUND');
        }

        // Check permissions
        if (ctx.user.role !== 'ADMIN' && ctx.user.role !== 'SUB_ADMIN' &&
            record.createdByUserId !== ctx.user.userId) {
          return createErrorResponse('No permission to query this order', 'PERMISSION_DENIED');
        }

        // Call NASKI query API
        const naskiResult = await rechargeService.queryNaskiOrderStatus(
          input.orderId,
          record.platOrderNum || undefined
        );

        let cardSellResult = null;

        console.log(`订单 ${input.orderId} NASKI支付查询结果:`, naskiResult);

        // 检查是否需要自动发金币 - NASKI查询成功的条件是code为200且status为5
        if (naskiResult.code === 200 && naskiResult.data?.status === 5) {
          // 重新获取最新的订单记录（可能在查询过程中状态已更新）
          const updatedRecord = await rechargeService.getRechargeRecordByOrderId(input.orderId);

          if (updatedRecord &&
              updatedRecord.status === 'COMPLETED' &&
              !updatedRecord.sellCardStatus) {

            Logger.info(`🎯 管理端查询发现订单 ${input.orderId} 支付成功但未发金币，开始自动发金币流程`, {
              orderId: input.orderId,
              trigger: 'admin_query'
            });

            try {
              cardSellResult = await rechargeService.executeCardSellAndNotify(input.orderId);
              Logger.info(`✅ 管理端查询触发的自动发金币完成`, {
                orderId: input.orderId,
                sellCardSuccess: cardSellResult.sellCardSuccess,
                telegramSent: cardSellResult.telegramSent,
                message: cardSellResult.message,
                trigger: 'admin_query'
              });
            } catch (error) {
              Logger.error(`❌ 管理端查询触发的自动发金币失败`, error, {
                orderId: input.orderId,
                trigger: 'admin_query'
              });
              cardSellResult = {
                success: false,
                message: `自动发金币失败: ${error instanceof Error ? error.message : '未知错误'}`
              };
            }
          }
        }

        return createSuccessResponse({
          localRecord: record,
          naskiResult,
          cardSellResult, // 包含发金币结果
        }, 'NASKI order status queried successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'NASKI order status query failed',
          'NASKI_QUERY_ERROR'
        );
      }
    }),

  /**
   * 获取可用的支付渠道 (需要认证)
   */
  getAvailableChannels: protectedProcedure
    .query(async () => {
      try {
        const channels = paymentService.getAvailableChannels();
        const channelInfo = channels.map(channel => ({
          value: channel,
          label: paymentService.getChannelDisplayName(channel),
          configured: paymentService.isChannelConfigured(channel)
        }));

        return createSuccessResponse({
          channels: channelInfo,
          count: channels.length
        }, '获取支付渠道成功');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : '获取支付渠道失败',
          'GET_CHANNELS_ERROR'
        );
      }
    }),

  /**
   * 获取可用的支付渠道 (公开接口，用于用户充值页面)
   */
  getPublicChannels: publicProcedure
    .query(async () => {
      try {
        const channels = paymentService.getAvailableChannels();
        const channelInfo = channels.map(channel => ({
          value: channel,
          label: paymentService.getChannelDisplayName(channel),
          configured: paymentService.isChannelConfigured(channel)
        }));

        return createSuccessResponse({
          channels: channelInfo,
          count: channels.length
        }, '获取支付渠道成功');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : '获取支付渠道失败',
          'GET_CHANNELS_ERROR'
        );
      }
    }),

  /**
   * 获取快捷金额配置 (公开接口，用于用户充值页面)
   */
  getPublicQuickAmounts: publicProcedure
    .query(async () => {
      try {
        // 从系统设置表获取配置
        const setting = await prisma.systemSetting.findUnique({
          where: { key: 'recharge_quick_amounts' }
        });

        let amounts: number[] = [100, 500, 1000, 2000, 5000, 10000]; // 默认值

        if (setting && setting.value) {
          try {
            amounts = JSON.parse(setting.value);
          } catch (error) {
            console.error('Failed to parse quick amounts config:', error);
          }
        }

        return createSuccessResponse({
          amounts
        }, '获取快捷金额配置成功');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : '获取快捷金额配置失败',
          'GET_QUICK_AMOUNTS_ERROR'
        );
      }
    }),


  /**
   * 获取购买价格信息配置 (公开接口，用于用户充值页面)
   */
  getPublicPurchasePriceInfo: publicProcedure
    .query(async () => {
      try {
        // 从系统设置表获取配置
        const setting = await prisma.systemSetting.findUnique({
          where: { key: 'purchase_price_info' }
        });

        let priceInfo: string = '5.5泰铢=1M金币'; // 默认值

        if (setting && setting.value) {
          priceInfo = setting.value;
        }

        return createSuccessResponse({
          priceInfo
        }, '获取购买价格信息成功');
      } catch (error) {
        console.error('Failed to get purchase price info:', error);
        return createErrorResponse(
          error instanceof Error ? error.message : '获取购买价格信息失败',
          'GET_PURCHASE_PRICE_INFO_ERROR'
        );
      }
    }),

  /**
   * 获取活跃产品配置（公开接口）
   */
  getActiveProductConfigs: publicProcedure
    .query(async () => {
      try {
        const { AdminService } = await import('../../services/adminService');
        const configs = await AdminService.getActiveProductConfigs();
        return createSuccessResponse(configs, 'Active product configs retrieved successfully');
      } catch (error) {
        console.error('Failed to get active product configs:', error);
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to get active product configs',
          'GET_PRODUCT_CONFIGS_ERROR'
        );
      }
    }),

  /**
   * 检查支付渠道配置状态
   */
  checkConfig: protectedProcedure
    .input(z.object({
      channel: z.nativeEnum(PaymentChannel).optional()
    }))
    .query(async ({ input }) => {
      try {
        if (input.channel) {
          // 检查特定渠道
          const isConfigured = paymentService.isChannelConfigured(input.channel);
          return createSuccessResponse({
            channel: input.channel,
            isConfigured,
            message: isConfigured ? `${input.channel}已配置` : `${input.channel}未配置，请联系管理员`
          }, '配置状态检查成功');
        } else {
          // 检查所有渠道
          const channels = Object.values(PaymentChannel).map(channel => ({
            channel,
            isConfigured: paymentService.isChannelConfigured(channel),
            displayName: paymentService.getChannelDisplayName(channel)
          }));

          return createSuccessResponse({
            channels,
            availableCount: channels.filter(c => c.isConfigured).length
          }, '配置状态检查成功');
        }
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : '配置检查失败',
          'CONFIG_CHECK_ERROR'
        );
      }
    }),

  /**
   * 用户端公开充值状态查询接口 - 无需认证
   */
  userCheckStatus: publicProcedure
    .input(z.object({
      orderId: z.string().min(1, 'Order ID cannot be empty'),
    }))
    .query(async ({ input }) => {
      try {
        const record = await rechargeService.getRechargeRecordByOrderId(input.orderId);

        if (!record) {
          return createErrorResponse('Order does not exist', 'ORDER_NOT_FOUND');
        }

        // 返回订单状态信息
        return createSuccessResponse({
          orderId: record.orderId,
          status: record.status,
          amount: record.amount,
          userId: record.userId,
          paymentChannel: record.paymentChannel,
          createdAt: record.createdAt,
          updatedAt: record.updatedAt,
          isPaid: record.status === 'COMPLETED'
        }, 'Order status retrieved successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to check order status',
          'USER_CHECK_STATUS_ERROR'
        );
      }
    }),

  /**
   * 用户端公开充值接口 - 无需认证
   */
  userRechargeCreate: publicProcedure
    .input(z.object({
      userId: z.number().int().positive('User ID must be a positive integer'), // 恢复必填
      amount: z.number().positive('Recharge amount must be greater than 0').max(100000, 'Recharge amount cannot exceed 100000'),
      paymentChannel: z.nativeEnum(PaymentChannel, {
        errorMap: () => ({ message: 'Payment channel must be TOPPAY, PAY668, or LSPPAY' })
      }).optional(), // 改为可选，支持自动选择
      paymentMethod: z.enum(['BankTransfer', 'qrPay'], {
        errorMap: () => ({ message: 'Payment method must be BankTransfer or qrPay' })
      }),
      transAccNo: z.string().min(1, 'Bank card number cannot be empty').regex(/^\d{10,20}$/, 'Bank card number must be 10-20 digits'),
      paymentName: z.string().min(1, 'Payer real name cannot be empty'),
      bankCode: z.string().optional(),
      customerEmail: z.string().email('Email format is incorrect').optional(),
      customerPhone: z.string().min(1, 'Phone number cannot be empty').optional(),
      extendParam: z.string().optional(),
      sessionId: z.string().min(1, 'Session ID is required'), // 用于标识用户会话
    }))
    .mutation(async ({ input }) => {
      try {
        // 只有在指定了渠道且不是LSPPAY时才验证bankCode
        if (input.paymentChannel && input.paymentChannel !== 'LSPPAY' && !input.bankCode) {
          return createErrorResponse(
            `Bank code is required for ${input.paymentChannel}`,
            'VALIDATION_ERROR'
          );
        }

        const result = await rechargeService.createRechargeOrder({
          userId: input.userId,
          amount: input.amount,
          paymentChannel: input.paymentChannel, // 可能为undefined，将使用自动选择
          paymentMethod: input.paymentMethod,
          createdByUserId: null, // 用户自助充值，无创建用户
          createdByName: '用户自助充值',
          transAccNo: input.transAccNo,
          paymentName: input.paymentName,
          bankCode: input.bankCode || '001', // 提供默认值，后端会根据选择的渠道调整
          customerEmail: input.customerEmail,
          customerPhone: input.customerPhone,
          extendParam: `SessionId: ${input.sessionId}${input.extendParam ? `, ${input.extendParam}` : ''}`,
        });

        return createSuccessResponse(result, 'User recharge order created successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to create user recharge order',
          'USER_RECHARGE_CREATE_ERROR'
        );
      }
    }),

  /**
   * 手动触发Telegram充值成功通知（用于前端确认支付成功后调用）
   */
  sendTelegramRechargeNotification: publicProcedure
    .input(z.object({
      orderId: z.string().min(1, 'Order ID cannot be empty'),
    }))
    .mutation(async ({ input }) => {
      try {
        // 获取订单信息
        const rechargeRecord = await rechargeService.getRechargeRecordByOrderId(input.orderId);

        if (!rechargeRecord) {
          return createErrorResponse('订单不存在', 'ORDER_NOT_FOUND');
        }

        // 检查Telegram是否配置
        if (!telegramService.isConfigured()) {
          return createErrorResponse('Telegram服务未配置', 'TELEGRAM_NOT_CONFIGURED');
        }

        // 发送Telegram通知（不管订单状态，都发送当前状态）
        const telegramData: TelegramNotificationData = {
          orderId: rechargeRecord.orderId,
          amount: parseFloat(rechargeRecord.amount.toString()),
          userId: rechargeRecord.userId,
          paymentChannel: rechargeRecord.paymentChannel,
          status: rechargeRecord.status === RechargeStatus.COMPLETED ? 'COMPLETED' :
                  rechargeRecord.status === RechargeStatus.FAILED ? 'FAILED' : 'CANCELLED',
          timestamp: rechargeRecord.updatedAt || rechargeRecord.createdAt,
          merchantId: process.env.TELEGRAM_MERCHANT_ID || ''
        };

        const success = await telegramService.sendRechargeNotification(telegramData);

        if (success) {
          return createSuccessResponse(
            {
              sent: true,
              orderId: input.orderId,
              status: rechargeRecord.status,
              merchantId: telegramData.merchantId
            },
            'Telegram充值通知发送成功'
          );
        } else {
          return createErrorResponse('Telegram通知发送失败', 'TELEGRAM_SEND_FAILED');
        }

      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : '发送Telegram通知失败',
          'TELEGRAM_NOTIFICATION_ERROR'
        );
      }
    }),

  /**
   * 执行售卡并发送Telegram通知（新的主要接口）
   * 当支付成功后调用此接口进行自动售卡
   */
  executeCardSellAndNotify: publicProcedure
    .input(z.object({
      orderId: z.string().min(1, 'Order ID cannot be empty'),
    }))
    .mutation(async ({ input }) => {
      try {
        // 获取充值记录
        const rechargeRecord = await rechargeService.getRechargeRecordByOrderId(input.orderId);

        if (!rechargeRecord) {
          return createErrorResponse('订单不存在', 'ORDER_NOT_FOUND');
        }

        // 检查订单状态
        if (rechargeRecord.status !== 'COMPLETED') {
          return createErrorResponse('订单未完成，无法执行售卡', 'ORDER_NOT_COMPLETED');
        }

        // 执行售卡并发送通知
        const result = await rechargeService.executeCardSellAndNotify(input.orderId);

        if (result.success) {
          return createSuccessResponse({
            orderId: input.orderId,
            sellCardSuccess: result.sellCardSuccess,
            message: result.message,
            telegramSent: result.telegramSent
          }, result.message);
        } else {
          return createErrorResponse(result.message, 'CARD_SELL_FAILED');
        }

      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : '售卡流程异常',
          'CARD_SELL_ERROR'
        );
      }
    }),
});
